<template>
  <a-layout has-sider class="components-layout-custom">
    <a-layout-sider width="125" v-model:collapsed="collapsed" :trigger="null" collapsible
                    :style="{ overflow: 'auto', height: '100vh', position: 'fixed', left: 0, top: 0, bottom: 0, zIndex: '10' }"
    >
<!--      <div class="logo"/>-->
      <div class="logo">{{ $CONFIG.APP_NAME }}</div>
      <a-menu v-model:selectedKeys="firstMenuSelectedKeys" theme="dark" mode="inline" @click="clickFirstMenu" :inlineIndent="10">
        <a-menu-item v-for="(item, index) in firstMenus" :key="item.name">
          <component :is="item.meta.icon"></component>
          <span :name="item.name">{{ item.title }}</span>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>

    <a-layout :style="{ marginLeft: marginLeftSider, position: 'relative' }">
      <div class="sub-menu" ref="subMenuRef" v-if="isHaveSubMenu" :style="{  }">

        <template v-for="(item, index) in secondMenus" :key="index">
          <div :class="item.meta.type === 'title'?'item-second':(activeKey === item.name ? 'item-third active':'item-third')" @click="clickSecondMenu(item)">
            <template v-if="item.meta.icon">
              <component :is="item.meta.icon" class="icon"></component>
            </template>
            <span>{{ item.title }} </span>
          </div>
          <template v-if="item.children && item.children.length">
            <div class="item-third" :class="activeKey === thirdItem.name ? 'active':''" v-for="(thirdItem, ii) in item.children" :key="ii" @click="clickSecondMenu(thirdItem)">
              <template v-if="thirdItem.meta.icon">
                <component :is="thirdItem.meta.icon" class="icon"></component>
              </template>
              <span>{{ thirdItem.title }}</span>
            </div>
          </template>
        </template>
      </div>
      <a-layout-content class="main-wrapper base-flex base-columns" :style="{}">
        <div class="collapsed-icon">
          <menu-unfold-outlined
              v-if="collapsed"
              class="trigger"
              @click="() => (collapsed = !collapsed)"
          />
          <menu-fold-outlined v-else class="trigger" @click="() => (collapsed = !collapsed)"/>
        </div>
        <div class="base-ml15 base-mr15 base-pl25">
          <basic-right-bar :breadcrumb="breadcrumb" :title="rightBarTitle"></basic-right-bar>
        </div>
        <div class="content-wrapper base-flex1">
          <router-view/>
        </div>
      </a-layout-content>

    </a-layout>
  </a-layout>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from "vue-router"
import BasicRightBar from '@/layouts/BasicRightBar.vue'
import cloneDeep from 'lodash.clonedeep'

const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $CONFIG = proxy.$CONFIG

let collapsed = ref(false)
const firstMenuSelectedKeys = ref([])
const secondMenuSelectedKeys = ref([])
const marginLeftSider = ref('125px')
const isHaveSubMenu = ref(false)
const firstMenus = ref([])
const secondMenus = ref([])
const subMenuRef = ref(null)
const route = useRoute()
const router = useRouter()
const rightBarTitle = ref('')
const breadcrumb = ref([]) // 面包屑
const activeKey = ref('') // 二级菜单高亮的路由name

watch(collapsed, (curr, old) => {
  // curr ? marginLeftSider.value = '80px' : marginLeftSider.value = '200px'
  getMarginLeftSiderWith()
})

/**
 * 监听路由变化，赋值高亮属性
 */
watch(route, (curr, old) => {
  breadcrumb.value = curr.meta.breadcrumb
  // console.log('面包屑', curr)
})

onMounted(() => {
  // 获取当前路由的父路由路径
  // const allRoutes = router.options.routes
  const allRoutes = $TOOL.data.get($CONFIG.ROUTE_INFO_KEY)

  // 这里不能直接从树结构中筛选，不然下边的currentRoute获取不到值
  // const allRoutes = filterMenuTree(cacheRoutes)
  // 过滤不显示的菜单
  firstMenus.value = filterMenuTree(cloneDeep(allRoutes))
  // firstMenus.value = allRoutes.filter((item) => {
  //   if(item.meta.showMenu) {
  //     return item
  //   }
  // })
  // console.log('firstMenus', firstMenus)

  setTimeout(() => {
    // 从未过滤的路由中取当前路由的信息，不然出现隐藏路由无法获取信息
    let currentRoute = findMenuItemByName(allRoutes, route.name)
    // 从已经过滤过的一级菜单取匹配的路由，不然会出现隐藏路由展示在二级菜单
    let parentRoute = findMenuItemByName(firstMenus.value, route.matched[0].name)
    // const parentRoute = route.matched[0]

    // console.log('全路由', allRoutes)
    // console.log('当前路由', currentRoute)
    // console.log('当前路由2', route)
    // 面包屑单独从当前路由信息里赋值
    breadcrumb.value = route.meta.breadcrumb

    rightBarTitle.value = currentRoute.title
    activeKey.value = currentRoute.name
    if (parentRoute && parentRoute['children'] && parentRoute['children'].length) {
      isHaveSubMenu.value = true
      // 这里上面一级菜单过滤过了，不再重复过滤
      secondMenus.value = parentRoute['children']
      if (secondMenus.value && secondMenus.value.length) {
        isHaveSubMenu.value = true
        secondMenuSelectedKeys.value = [currentRoute.name]
      } else {
        isHaveSubMenu.value = false
      }
    } else {
      isHaveSubMenu.value = false
    }
    firstMenuSelectedKeys.value = [parentRoute.name]
    getMarginLeftSiderWith()
  }, 180)
})

/**
 * 筛选出菜单树可以显示的路由
 * @returns {*[]}
 */
const filterMenuTree = (tree) => {
  return tree.filter(item => {
    if (item.meta && item.meta.showMenu) {
      if (item.children) {
        // Recursively filter children
        item.children = filterMenuTree(item.children)
      }
      return true
    }
    return false
  })
}

const findMenuItemByName = (tree, targetName) => {
  for (const item of tree) {
    if (item.name === targetName) {
      return item;  // 找到匹配项，返回该项
    } else if (item.children) {
      const result = findMenuItemByName(item.children, targetName);  // 递归查找子级
      if (result) {
        return result;  // 如果在子级中找到匹配项，返回该项
      }
    }
  }
  return null;  // 没有找到匹配项
}

// 获取主体距离左侧的距离
const getMarginLeftSiderWith = () => {
  const collapsedValue = collapsed.value
  const isHaveSubMenuValue = isHaveSubMenu.value
  // console.log(collapsedValue)
  // console.log(isHaveSubMenuValue)
  if (!collapsedValue && isHaveSubMenuValue) {
    // 展开，并且有子级
    marginLeftSider.value = '250px'
    nextTick(() => {
      subMenuRef.value.style = 'left: 125px'
    })
  } else if (!collapsedValue && !isHaveSubMenuValue) {
    // 展开，无子级
    marginLeftSider.value = '125px'
  } else {
    // 收起
    marginLeftSider.value = '80px'
    if (isHaveSubMenuValue) {
      // 125-80 = 45
      nextTick(() => {
        subMenuRef.value.style = 'left: -45px'
      })
    }
  }
}

// 点击一级菜单事件
const clickFirstMenu = (item) => {
  const currentMenu = firstMenus.value.find(ele => ele.name === item.key)
  if (currentMenu.children) {
    // console.log(currentMenu)
    secondMenus.value = currentMenu.children.filter((route) => {
      if (route.meta.showMenu) {
        // 只展示显示的路由
        return route
      }
    })

    if (secondMenus.value && secondMenus.value.length) {
      isHaveSubMenu.value = true
    } else {
      isHaveSubMenu.value = false
    }

  } else {
    isHaveSubMenu.value = false
    secondMenus.value = []
  }

  // 如果没有二级菜单，有path可以跳转
  if (currentMenu.path && !isHaveSubMenu.value) {
    secondMenuSelectedKeys.value = []
    rightBarTitle.value = currentMenu.title
    router.push(currentMenu.path)
  }

  collapsed.value = false
  getMarginLeftSiderWith()
}

// 点击二级菜单事件
const clickSecondMenu = (item) => {
  // console.log(item)
  // const currentMenu = secondMenus.value[item.key]
  // const currentMenu = secondMenus.value.find(ele => ele.name === item.key)
  if (item.meta.type === 'title') {
    // 标题点击无事件
    return false
  }
  activeKey.value = item.name
  rightBarTitle.value = item.title
  router.push(item.path)
}

</script>
<style lang="scss">
.components-layout-custom {
  .logo {
    background: rgba(255, 255, 255, 0.3);
    //margin: 16px;
    text-align: center;
    color: #ffffff;
    padding: 20px 0;
    font-size: 18px;
    margin-bottom: 10px;
  }

  .sub-menu {
    width: 125px;
    background: #fff;
    position: fixed;
    //overflow: auto; // 放开以后影响右侧的收起按钮
    height: 100vh;
    left: 125px;
    top: 0;
    bottom: 0;
    z-index: 9;
    transition: all .3s ease-in-out;
    padding-top: 20px;
    overflow-y: scroll;

    .item-second {
      color: #999;
      font-size: 12px;
      margin: 10px 0 12px 16px;
      height: auto;
      line-height: 12px;
      //text-overflow: ellipsis;
      //padding-inline: 16px;
      //margin-inline: 4px;
      //margin-block: 4px;
      //width: calc(100% - 8px);
      //&:hover {
      //  background: none !important;
      //  color: #999 !important;
      //  cursor: default;
      //}

      position: relative;
      padding-top: 20px;
      &:before {
        position: absolute;
        left: -8px;
        top: 0;
        content: ' ';
        width: 98%;
        height: 1px;
        background: #e0e0e0;
      }
      &:first-child {
        padding-top: 0;
        &:before {
          display: none;
        }
      }
    }
    .item-third {
      border-radius: 2px;
      font-size: 14px;
      //height: 36px;
      line-height: 36px;
      margin: 0 8px 4px;
      padding: 0 8px;
      cursor: pointer;
      .icon {
        margin-right: 8px;
      }
      &.active {
        background: rgba(21,91,212,.08);
        color: #155bd4;
      }
    }
  }

  .main-wrapper {
    .collapsed-icon {
      position: absolute;
      left: 0px;
      top: 20px;
      background: rgba(0, 0, 0, .06);
      text-align: center;
      width: 30px;
      height: 30px;
      display: flex;
      justify-content: center;
      align-content: center;
      border-radius: 0 20px 20px 0;

      .trigger {
        line-height: 30px;
        font-size: 13px;
        //padding: 0 24px;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #1890ff;
        }
      }
    }

    margin: 20px 0 0 0;
    padding: 0;
    // 有个margin-top是20
    min-height: calc(100vh - 20px);
    overflow: initial;
    box-sizing: border-box;
    min-width: 960px;
    width: auto;

    .content-wrapper {
      //background: #ffffff;
      padding: 15px;
    }
  }
}

</style>
